package com.jinbai.servlet.album;

import com.jinbai.util.DBUtil;
import com.jinbai.util.Log;
import jdk.nashorn.internal.objects.annotations.Setter;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/studio/album/add.do")
public class AddDoServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        final String aid = req.getParameter("aid");
        final String[] tidArr = req.getParameterValues("add-tid");
        String pre = "insert into relations (aid, tid) values %s";
        StringBuilder s = new StringBuilder();
        for (String tid : tidArr) {
            s.append("(").append(aid).append(", ").append(tid).append("), ");
        }
        s.delete(s.length() - 2, s.length());
        final String sql = String.format(pre, s);

        try (Connection con = DBUtil.connection()) {
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                Log.println("执行SQL：" + ps);
                ps.executeUpdate();
            }
        }
        Log.println("向专辑中添加歌曲成功！");
        resp.sendRedirect("/studio/album/albumInfo.html?aid=" + aid);
    }
}
